﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Group3.MediaTool.Core;
using Group3.MediaTool.Interface;

namespace Group3.MediaTool.Data.IO
{
    public class DataDefinitionIO
    {
        /// <summary>
        /// Adds the application path to a relative path string
        /// </summary>
        /// <param name="relativePath">relative Path of the location</param>
        /// <returns></returns>
        private string addBaseDirectoryToPath(String relativePath)
        {
            String fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath);
            return fullPath;
        }


        /// <summary>
        /// Overwrites or creates a new file containing the specified strin
        /// </summary>
        /// <param name="relativePath">relative path to the application directory</param>
        /// <param name="fileName">Name of the file</param>
        /// <param name="text">String that should be stored in the file</param>
        public void deleteAndWriteFile(String relativePath, String fileName, String text)
        {
            string fullPath = addBaseDirectoryToPath(relativePath);
            if (!Directory.Exists(fullPath))
                Directory.CreateDirectory(fullPath);
            if (File.Exists(Path.Combine(fullPath + fileName)))
                File.Delete(Path.Combine(fullPath + fileName));

            StreamWriter sw = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath + fileName));
            sw.Write(text);
            sw.Close();
        }

        /// <summary>
        /// Method to take care of wrinting the XML-File in case it is in access by multiple threads
        /// </summary>
        /// <param name="doc">XML Document</param>
        /// <param name="firstRun">True for retry if failed, false if only one try should be done</param>
        public void writeXMLFile(XDocument doc)
        {
            string fullPath = StaticConfig.pathDataDefinitionFile;
            int counter = 0;
            while (true)
            {
                try
                {
                    doc.Save(fullPath);
                    counter++;
                    break;
                }
                catch (Exception e)
                {
                    if (counter > 100)
                    {
                        DataDefinitionIO ddio = new DataDefinitionIO();
                        ddio.writeLogFile(e.ToString(), "Error");
                        break;
                    }
                    System.Threading.Thread.Sleep(50);
                }
            }
        }

        /// <summary>
        /// Writes continues log-file for every day. 
        /// </summary>
        /// <param name="s">messsage that will be shown in the logfile</param>
        /// <param name="type">Classification of the Message like "Error", "Warning" or "Info" Defaults to "Info"</param>
        public void writeLogFile(String s, String type)
        {
            if (String.IsNullOrEmpty(type))
            {
                type = "Info";
            }

            if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ressources")))
                Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ressources"));
            String _path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ressources\\Log" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + ".log");
            String logEntry = "" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "_" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + "  [" + type + "]   " + s + Environment.NewLine;

            if (!File.Exists(_path))
            {
                StreamWriter sw = new StreamWriter(_path);
                sw.Write(logEntry);
                sw.Close();
            }
            else
            {
                File.AppendAllText(_path, logEntry);
            }

        }

        public List<KeyValuePair<String,String>> readConfig()
        {
            List<KeyValuePair<String, String>> list = new List<KeyValuePair<String, String>>();

            KeyValuePair<String, String> kvp1 = new KeyValuePair<string, string>("database", "1");

            String datafile= Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataDefinition\\DataDefinition.xml");
            //String datafile = "C:\\Users\\Armari\\VS_Projekte\\g3MediaTool\\DataDefinition\\DataDefinition.xml";
            KeyValuePair<String, String> kvp2 = new KeyValuePair<string, string>("DataDefinitionFile", datafile);

            String datafolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataDefinition\\");
            //String datafolder= "C:\\Users\\Armari\\VS_Projekte\\g3MediaTool\\DataDefinition\\";
            KeyValuePair<String, String> kvp3 = new KeyValuePair<string, string>("DataDefinitionFolder", datafolder);

            String databaseConn = "Server=localhost;Integrated security=SSPI;database=Group3_BookTool_LiveTest";
            //String databaseConn = "Server=localhost;Integrated security=SSPI;database=Group3_BookTool";

            KeyValuePair<String, String> kvp4 = new KeyValuePair<string, string>("DATABASECONNECTION", databaseConn);


            list.Add(kvp1);
            list.Add(kvp2);
            list.Add(kvp3);
            list.Add(kvp4);

            return list;
        }

        public void writeConfig()
        {


        }


    }
}
